package com.aerozhonghuan.logisticsmall.modules.home.search;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.aerozhonghuan.foundation.base.BaseActivity;
import com.aerozhonghuan.foundation.eventbus.EventBusManager;
import com.aerozhonghuan.logisticsmall.R;
import com.aerozhonghuan.logisticsmall.framework.DB.DBAdapter;
import com.aerozhonghuan.logisticsmall.modules.common.IMainView;
import com.aerozhonghuan.logisticsmall.modules.common.MainActivity;
import com.aerozhonghuan.logisticsmall.modules.common.entity.GoodsObject;
import com.aerozhonghuan.logisticsmall.modules.common.event.TabNumberChangedEvent;
import com.aerozhonghuan.logisticsmall.modules.home.AddProductToGouwuche;
import com.aerozhonghuan.logisticsmall.modules.home.ChangeProductGouwucheNum;
import com.aerozhonghuan.logisticsmall.modules.home.logic.HomePageInfoRequest;
import com.aerozhonghuan.logisticsmall.modules.home.search.beans.SearchBean;
import com.aerozhonghuan.logisticsmall.utils.CommunityUtils;
import com.aerozhonghuan.logisticsmall.utils.StatusBarUtil;
import com.aerozhonghuan.logisticsmall.widget.ProgressDialogIndicator;
import com.aerozhonghuan.oknet2.CommonCallback;
import com.aerozhonghuan.oknet2.CommonMessage;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ChenLin on 2019/5/22 10:01.Email&WeChat:7877409@163.com
 */
public class SearchProductActivity extends BaseActivity implements View.OnClickListener,
        AddProductToGouwuche, AbsListView.OnScrollListener, ChangeProductGouwucheNum {

    public static final String TAG = SearchProductActivity.class.getSimpleName();
    public static SearchProductActivity mSearchProductActivity;
    private boolean DEBUG = com.blankj.utilcode.util.AppUtils.isAppDebug();
    private TextView mTitle;
    private List<GoodsObject> mGoodsObjects = new ArrayList<GoodsObject>();
    //private MyAdapter mAdapter;
    private ProductListAdapter mProductListAdapter;
    private int mPageMaxSize = 200;
    private int currentPage = 1;
    private int mTotalPage = 0;
    private int mLastItem;
    private int mCountItem; //总共有多少itme
    private int mCountRecord;
    private DBAdapter mDbAdapter;
    private GridView mProductGridView;
    private String mFrom;
    private TextView mNoProducTextView;
    private ImageView mTitleImageView;
    private int mSourceId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.goods_for_category_activity);
        StatusBarUtil.setLightStatusBar(this, true);
        mDbAdapter = new DBAdapter(this);
        initView();
    }

    private void initView() {
        findViewById(R.id.back_btn).setOnClickListener(this);
        mSearchProductActivity = this;
        mNoProducTextView = (TextView) findViewById(R.id.no_products);

        mTitle = (TextView) findViewById(R.id.title);
        mTitleImageView = (ImageView) findViewById(R.id.title_img);
        Intent intent = getIntent();
        String title = intent.getStringExtra("keyword");
        mCountRecord = intent.getIntExtra("count_record", 0);
        int cid = intent.getIntExtra("cid", 0);
        int csId = intent.getIntExtra("businessid", 0);
        mFrom = intent.getStringExtra("from");
        boolean isSecondLevel = intent.getBooleanExtra("second_level", true);
        mGoodsObjects = (ArrayList<GoodsObject>) intent.getSerializableExtra("search_res");
        if (mGoodsObjects != null && mGoodsObjects.size() > 0) {
            mSourceId = 3;
        } else {
            mSourceId = 6;
        }
        mTitle.setText(title);
        if (!TextUtils.isEmpty(mFrom) && mFrom.equalsIgnoreCase("advert")) {
            mProductListAdapter = new ProductListAdapter(this, mDbAdapter, "search_product_activity", mSourceId);
        } else {
            if (!TextUtils.isEmpty(mFrom) && mFrom.equalsIgnoreCase("community")) {
                getGowucheProductSize();
            }
            mProductListAdapter = new ProductListAdapter(this, mDbAdapter, "search_product_activity", mSourceId);
        }

        mProductGridView = (GridView) findViewById(R.id.product_gridview);
        mProductGridView.setAdapter(mProductListAdapter);

        if (mGoodsObjects != null && mGoodsObjects.size() > 0) {
            ArrayList<GoodsObject> gouwucheList = mDbAdapter.getAllData();
            mProductListAdapter.setData(reSetValue(gouwucheList, mGoodsObjects));
        }
        Log.d("community2", "csid=" + csId + "  cid=" + cid);
        if (csId != 0) {
            doSearchBusinessDetail(csId);
        } else if (cid != 0) {
            doSearchQuery(cid, isSecondLevel);
        }
    }

    private void getGowucheProductSize() {
        int gouwucheSize = 0;
        ArrayList<GoodsObject> getData = new DBAdapter(this).getAllData();
        for (GoodsObject product : getData) {
            if (product.getIsCheck() == 0) {
                gouwucheSize += product.getIntoGouwucheSize();
            }
        }
        if (gouwucheSize > 0) {
            EventBusManager.post(new TabNumberChangedEvent(IMainView.TAB_CART_FRAGMENT, gouwucheSize));
        }
    }

    private List<GoodsObject> reSetValue(List<GoodsObject> gouwucheList, List<GoodsObject> list) {
        if (gouwucheList == null || gouwucheList.size() == 0) {
            return list;
        }
        if (DEBUG) {
            Log.d("community2", "gouwuchesize:" + gouwucheList.size() + "   list.size:" + list.size());
        }
        for (GoodsObject gouwucheP : gouwucheList) {
            for (GoodsObject p : list) {
                if (gouwucheP.getPvsid() == p.getPvsid()) {
                    int intoGouwucheSize = gouwucheP.getIntoGouwucheSize();
                    p.setIntoGouwucheSize(intoGouwucheSize);
                }
            }
        }
        mGoodsObjects = list;
        return list;
    }

    private void doSearchBusinessDetail(int csid) {
    }

    private void doSearchQuery(int cid, boolean secondLevel) {
        HomePageInfoRequest.list(cid + "", "100", "1", this,
                new ProgressDialogIndicator(this), new CommonCallback<SearchBean>() {
                    @Override
                    public void onSuccess(SearchBean messsageBodyObject, CommonMessage commonMessage, String allResponseString) {
                        ArrayList<GoodsObject> goods = messsageBodyObject.datalist;
                        if (goods != null && goods.size() > 0) {
                            List<GoodsObject> gouwucheList = mDbAdapter.getAllData();
                            mProductListAdapter.setData(reSetValue(gouwucheList, goods));
                        } else {
                            mNoProducTextView.setVisibility(View.VISIBLE);
                        }
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!TextUtils.isEmpty(mFrom) && mFrom.equals("advert")) {
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
                return true;
            } else {
                return super.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, MainActivity.class);
        switch (v.getId()) {
            case R.id.back_btn:
                if (!TextUtils.isEmpty(mFrom) && mFrom.equals("advert")) {
                    startActivity(intent);
                }
                finish();
                break;
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (mLastItem == mCountItem && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
            currentPage++;
            if (mTotalPage - 1 >= currentPage) {
                Log.d(TAG, "mPageCount:" + mTotalPage + "  currentPage:" + (currentPage));
                //doSearchQuery();
            }
        }
        switch (scrollState) {
            case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
            case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                break;
            case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                mProductListAdapter.notifyDataSetChanged();
                break;

            default:
                break;
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        mLastItem = firstVisibleItem + visibleItemCount;

    }

    @Override
    public void updateData(int productSize) {
        Log.d(CommunityUtils.TAG, "CategoryResultActivity update" + productSize);
        if (productSize > 0) {
            EventBusManager.post(new TabNumberChangedEvent(2, productSize));
        }
    }

    @Override
    public void change(GoodsObject product) {
        if (mGoodsObjects == null) {
            return;
        }
        for (GoodsObject p : mGoodsObjects) {
            if (p.getPvsid() == product.getPvsid()) {
                p.setIntoGouwucheSize(product.getIntoGouwucheSize());
            }
        }
        mProductListAdapter.setData(mGoodsObjects);
    }
}
